package com.ocl.www.controller;

import java.util.*;

import javax.servlet.http.HttpServletRequest;

import com.ocl.www.domain.LyUser;
import com.ocl.www.security.ShiroCasConfiguration;
import com.ocl.www.service.LyUserService;
import com.ocl.www.utils.OutServerUntils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import com.ocl.www.basic.BasicController;


//import com.ocl.www.document.Test;
import com.ocl.www.domain.User;
import com.ocl.www.service.UserService;
import com.ocl.www.utils.ResourceBundleUtils;

@RestController
@RequestMapping("/login")
public class LoginController extends BasicController {
	
	@Autowired
	private UserService userService;

	@Autowired
	private LyUserService lyUserService;
	
	@Autowired
	private EhCacheManager em;
//	@Autowired
//	private ShiroCasRealmImpl  shiroCasRealm;
	
	private Logger log = Logger.getLogger(LoginController.class);
	
	
	/**
	 * 
	 * @Title: UserController
	 * @Description: 进入个人首页
	 * @param: @param user
	 * @param: @return
	 * @return: User
	 * @throws
	 */
	@RequestMapping(value = "/personIndex", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ApiOperation(value="进入个人首页", notes="（已过时，不推荐使用）")
	@ApiImplicitParam(name = "user", value = "用户详细实体User", required = true, dataType = "com.ocl.www.domain.User")
	public ModelAndView personIndex (User user) {
//		User user = new User();
//		user.setUserName(SecurityUtils.getSubject().getPrincipal().toString());
//		//user.setPassword("123123");
//		try {
//			user = userService.findUserInfo(user);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
		///return "redirect:http://localhost/person.html";
//		System.out.println("进入。。。");
		ModelAndView mav = new ModelAndView();
		mav.setViewName("redirect:"+ResourceBundleUtils.getProperty("project.page.host")+"/person.html");
		
		return mav;
	}
	
	/**
	 * login/userLogin
	 * @Title: LoginController
	 * @Description: 用户登录
	 * @param: @return
	 * @return: String
	 * @throws
	 */
	@RequestMapping(value = "/testLogin", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public String testlogin(HttpServletRequest request){
		System.out.println("服务器地址:"+request.getServerName());   // 获取服务器地址，如：localhost
		System.out.println("服务器端口:"+request.getServerPort())  ; // 获取服务器端口，如8080
		System.out.println("项目名称:"+request.getContextPath()) ;  // 获取项目名称，如：TestSytem
		System.out.println("本地地址:"+request.getLocalAddr())  ; // 获取本地地址，如：127.0.0.1
		return "ok!";
	}

	/**
	 * 登录
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/recordPageUrl", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ResponseBody
	public Map<String,Object> recodePageUrl(@RequestBody Map<String,Object> map,HttpServletRequest request){


		request.getSession().setAttribute("page",map.get("page"));
		request.getSession().setAttribute("pageId",map.get("id"));
		map.put("info", ShiroCasConfiguration.loginUrl);
		map.put("status","s");
		log.info(request.getSession().getAttribute("page"));
		return map;

	}

	/**
	 *
	 * logout
	 */
	@ApiOperation(value="用户登出", notes="用户登出")
	@RequestMapping(value = "/userlogout", method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public Map<String,Object> userlogout(){
		Map<String,Object> map = new HashMap<String,Object>();
		try{
			SecurityUtils.getSubject().logout();
			map.put("status","s");
			map.put("info",ShiroCasConfiguration.casLogoutUrl);
		}catch (Exception e){
			map.put("status","s");
			map.put("info",e.getMessage());
		}

		return map;
	}

	@RequestMapping(value = "/isLogin",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public Map<String,Object> isLogin(){

		Map<String,Object> map = new HashMap<String,Object>();
		try{
			log.info(SecurityUtils.getSubject().getPrincipals().asList());

			LyUser lyUser = new LyUser();
			lyUser.setUserId(String.valueOf(SecurityUtils.getSubject().getPrincipal()));
			lyUser = lyUserService.getUserInfo(lyUser);
			JSONObject lyUserjson = new JSONObject();
			lyUserjson.put("userId",lyUser.getUserId());
			lyUserjson.put("userName",lyUser.getUserName());
			lyUserjson.put("userImg",lyUser.getUserImg());

			map.put("status","s");
			map.put("info",lyUserjson);

		}catch (NullPointerException e){
			map.put("status","e");
			map.put("info",e.getMessage());
		} catch (Exception e) {
			map.put("status","e");
			map.put("info",e.getMessage());
		}
		return  map;
	}

//	@RequestMapping(value = "/index", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
//	public ModelAndView hello(Map<String,Object> map){
//
//		map.put("hello","from TemplateController.helloHtml");
//		return new ModelAndView("lanyou/index");
//
//	}

	/**
	 * description:登录时验证是否第一次登录
	 *
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/userLogin", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ApiOperation(value="用户登录", notes="登录时会验证是否第一次登录，第一次则将cas返回的数据插入ocl_user表中")
	public ModelAndView userLogin () {
		User user = null;
		try {
			User loginUser = new User();
//			18620852973,{realName=, nickName=灏辫繖鏍峰惂, sex=1, mobile=18620852973, userId=130, email=xlh@callell.cn, account=18620852973}
//			log.info(SecurityUtils.getSubject().getPrincipals().asList());
//			Class<? extends PrincipalCollection> cls = SecurityUtils.getSubject().getPrincipals().getClass();
//			System.out.println(cls.getDeclaredMethods());
//			Method[] m = cls.getDeclaredMethods();
//			for(int i = 0; i < m.length; i++) {
//				System.out.println("method = " + m[i].toString());
//			}
			
			Set<?> s = SecurityUtils.getSubject().getPrincipals().asSet();
			Object[] obj = new Object[2];
			int obji = 0;
			Iterator<?> it = s.iterator();
			while(it.hasNext()){
				obj[obji] = it.next();
				log.info(obj.getClass());
				log.info(obj.toString());
				obji++;
			}
			Map<String,String> map = (Map<String, String>) obj[1];
//			log.info(map.get("realName"));
//			log.info(map.get("nickName"));
//			log.info(map.get("sex"));
//			log.info(map.get("mobile"));
//			log.info(map.get("userId"));
//			log.info(map.get("email"));
//			log.info(map.get("account"));
			//未配置，无输出
//			log.debug(map);
			//已配置，可控制台输出
//			log.info(map);
//			log.error(map);
//			log.fatal(map);
			String nickname = null;
			try {
				nickname = new String(map.get("nickName").getBytes(),"UTF-8");
			}catch (NullPointerException e){
				nickname="无名氏";
			}
//			String sex = map.get("sex");
//			String mobile = map.get("mobile");
			String userId = map.get("userId");
//			String email = map.get("email");
			String account = map.get("account");
			String headImage = "/922f0ca8-c0f7-4185-9bc4-dec4df3a7c5d_touxiang.jpg";
			String sex = map.get("sex")==null?map.get("sex"):"0";
			String mobile = map.get("mobile")==null?map.get("mobile"):map.get("account");
			String email = map.get("email")==null?map.get("email"):"callbell@2016.cn";

			loginUser.setUserName(account);
			loginUser.setUserId(Integer.valueOf(userId));
			log.info("username:"+loginUser.getUserName());
			user = userService.findUserInfo(loginUser);
			
			if(user==null){
				user = new User();
				user.setNickName(nickname);
				user.setSex(Integer.valueOf(sex));
				user.setMobile(mobile);
				user.setUserId(Integer.valueOf(userId));
				user.setEmail(email);
				user.setUserName(account);
				user.setHeadImage(headImage);
				int c = userService.addUserInfo(user);
				log.info(c);
				if(c==1){
					log.info("登录时添加用户成功");
				}else{
					log.info("登录时添加用户失败");
				}
			}
			log.info(em.getCacheManager().cacheExists("shiroCache"));
			//权限校验。判断是否包含权限。
			Subject subject = SecurityUtils.getSubject();
			//具体响应ShiroDbRealm。doGetAuthorizationInfo，判断是否包含此url的响应权限
			boolean isPermitted = subject.isPermitted("注册");
			if(isPermitted == true) {
				log.info("该用户拥有此权限：注册");
			}else{
				log.info("该用户没有此权限：注册");
			}

			
//			log.info(em.getCacheManager().cacheExists("shiroCache"));
//			//权限校验。判断是否包含权限。
//			Subject subject = SecurityUtils.getSubject();
//			//具体响应ShiroDbRealm。doGetAuthorizationInfo，判断是否包含此url的响应权限
//			boolean isPermitted = subject.isPermitted("注册");
//			if(isPermitted == true) {
//				log.info("该用户拥有此权限：注册");
//			}else{
//				log.info("该用户没有此权限：注册");
//			}

//			em.getCache("shiroCache").remove("user_name");
//			em.getCache("shiroCache").remove("user_id");
//			em.getCache("shiroCache").put("user_name", user.getUserName());
//			em.getCache("shiroCache").put("user_id",user.getUserId());
//			log.info(em.getCache("shiroCache").get("user_id"));

		    //关于jvm加载和卸载的测试
//			com.ocl.www.document.Test ss = new com.ocl.www.document.Test();
//		    ss.aa();
//		    tt();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		ModelAndView mav = new ModelAndView();
		//String pageAddress = ResourceBundleUtils.getProperty("project.page.host");
		//log.info("ocl-properties文件中的pageAddress常量："+pageAddress);
		mav.setViewName("redirect:"+ResourceBundleUtils.getProperty("project.page.host")+"/index2.html");
		return mav;
	}

	/**
	 * description:该函数已经废弃（别删）
	 *
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/addUser", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ApiOperation(value="用户添加", notes="(已过时，不推荐使用)")
	public Map<String,Object> addUser () {
		User user = null;
		Map<String,Object> map1 = new HashedMap();
		try {
			User loginUser = new User();
//			18620852973,{realName=, nickName=灏辫繖鏍峰惂, sex=1, mobile=18620852973, userId=130, email=xlh@callell.cn, account=18620852973}
			log.info(SecurityUtils.getSubject().getPrincipals().asList());

			Set<?> s = SecurityUtils.getSubject().getPrincipals().asSet();
			Object[] obj = new Object[2];
			int obji = 0;
			Iterator<?> it = s.iterator();
			while(it.hasNext()){
				obj[obji] = it.next();
				log.info(obj.getClass());
				log.info(obj.toString());
				obji++;
			}
			Map<String,String> map = (Map<String, String>) obj[1];
//			log.info(map.get("realName"));
//			log.info(map.get("nickName"));
//			log.info(map.get("sex"));
//			log.info(map.get("mobile"));
//			log.info(map.get("userId"));
//			log.info(map.get("email"));
			log.info(map.get("account"));
			//未配置，无输出
			log.debug(map);
			//已配置，可控制台输出
			log.info(map);
			log.error(map);
			log.fatal(map);
			String nickname = null;
			try {
				nickname = new String(map.get("nickName").getBytes(),"UTF-8");
			}catch (NullPointerException e){
				nickname="无名氏";
			}
			String sex = map.get("sex");
			String mobile = map.get("mobile");
			String userId = map.get("userId");
			String email = map.get("email");
			String account = map.get("account");

			loginUser.setUserName(account);
			loginUser.setUserId(Integer.valueOf(userId));
			log.info("username:"+loginUser.getUserName());
			user = userService.findUserInfo(loginUser);

			if(user==null){
				user = new User();
				user.setNickName(nickname);
				user.setSex(Integer.valueOf(sex));
				user.setMobile(mobile);
				user.setUserId(Integer.valueOf(userId));
				user.setEmail(email);
				user.setUserName(account);
				int c = userService.addUserInfo(user);
				log.info(c);
				if(c==1){
					log.info("登录时添加用户成功");
					map1.put("info","1");
					map1.put("tip","登录成功");
					return map1;
				}else{
					log.info("登录时添加用户失败");

					map1.put("info","0");
					map1.put("tip","登录失败");
					return map1;
				}
			}
		} catch (Exception e) {
			//e.printStackTrace();
			map1.put("info","0");
			map1.put("tip","登录失败:"+e.getMessage());
			return map1;
		}

		return map1;

	}


	@ApiOperation(value="用户添加", notes="(已过时，不推荐)")
	@RequestMapping(value = "/getUserInfo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public List<String> getUserInfo () {
		User user = null;
		try {
			User loginUser = new User();
			loginUser.setUserName(SecurityUtils.getSubject().getPrincipal().toString());
			user = userService.findUserInfo(loginUser);
			
		} catch (Exception e) {
			e.printStackTrace();
		}

		List<String> list = new ArrayList<String>();
		list.add("emil");
		list.add("Tobias");
		list.add("linux");
		return list;
	}

	@ResponseBody
	@RequestMapping(value = "/testdiaoyong", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public void testdiaoyong(@RequestBody Map<String,String> maptemp) {
//		String teststr = req.getParameter("mobilePhone");
//		System.out.println(teststr);
//		String ttargetURL = "https://clmp.callbell.cn/sso/api";
//		String ttargetURL = "http://192.168.1.39/cas-server-webapp/api";
//
//		Date d = new Date();
//		Timestamp timestamp = new Timestamp(d.getTime());
//		String plainText = "ABCELLLLappidCALLBELL1mtypequerytimestamptimestampABCELLLL";
//		String sign = MD5Util.encryption(plainText);
//		String tinput = "appid=CALLBELL1&mtype=query&timestamp="+timestamp+"&sign="+sign+"&params={mobilePhone:15017573651}";
//		String tdata = OutServerUntils.callInterface(ttargetURL,tinput,"GET","application/x-www-form-urlencoded");

//		测试数据
//		http://192.168.1.39/cas-server-webapp/api
//		appid=CALLBELL1&mtype=query&timestamp=timestamp&sign=73fadcd81c2970c0b602d026308266b7&params={mobilePhone:15017573651}
//		String tinput = "appid=CALLBELL1&mtype=register&timestamp=timestamp&sign=7a59fb69730b7b90ebca61bde4e27af5&params={account:15989174229,password:123456,open_id:123456,user_type:1}";
//		String tdata = OutServerUntils.CallInterface(ttargetURL,tinput,"","multipart/form-data");

//		try {
//			System.out.println(new String(tdata.getBytes(),"utf-8"));
//		} catch (UnsupportedEncodingException e) {
//			e.printStackTrace();
//		}

//		post请求方式
//		OutServerUntils hd = new OutServerUntils();
//		Map<String,String> map = new HashMap();
//		map.put("appid","CALLBELL1");
//		map.put("mtype","query");
//		map.put("timestamp","timestamp");
//		map.put("sign","73fadcd81c2970c0b602d026308266b7");
//		map.put("params","{mobilePhone:15017573651}");
//		hd.post("http://192.168.1.39/cas-server-webapp/api",map);

//		get请求方式(参数写法有问题)
		OutServerUntils hd = new OutServerUntils();
		String sendstr = "appid=CALLBELL1&mtype=query&timestamp=timestamp&sign=73fadcd81c2970c0b602d026308266b7&params={mobilePhone:15017573651}";
		String content = hd.get("http://192.168.1.39/cas-server-webapp/api",sendstr);
		System.out.println(content);
	}

}
